package cn.fanyc.action.blockchain.fbc.org2.controller.issue;

import cn.fanyc.anvil.sdk.common.domain.RestDomain;
import cn.fanyc.action.blockchain.fbc.org2.config.GlobalConstants;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.ContractException;
import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.Network;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeoutException;

/**
 * 账号管理控制器
 *
 * @author Fanyc
 * @date 2020/6/18 13:59
 */
@RestController
@RequestMapping("/issue")
public class IssueController {

    /**
     * 日志记录器
     */
    private final Logger logger = LoggerFactory.getLogger(IssueController.class);

    /**
     * Fabric网关
     */
    @Autowired
    private Gateway gateway;

    /**
     * 购买票据
     *
     * @param buyer 发布者
     * @param key   票据KEY
     * @return 购买结果
     */
    @RequestMapping("/buy")
    public RestDomain<?> buy(String buyer, String key, String issuer, String paperNumber, String owner) {
        logger.info("==========购买票据：购买者={}，票据KEY={}，发行者={}，票据号={}，拥有者={}==========", buyer, key, issuer, paperNumber, owner);
        try {
            // get the network and contract
            Network network = gateway.getNetwork(GlobalConstants.CHANNEL_NAME);

            Contract contract = network.getContract(GlobalConstants.CONTRACT_FBC);

            byte[] result = contract.submitTransaction("buy", issuer, paperNumber, owner, buyer, "10001", "2020-07-20");
            if (result != null) {
                System.out.println("购买结果：" + new String(result));
            } else {
                System.out.println("购买结果：null");
            }
        } catch (InterruptedException | TimeoutException | ContractException e) {
            e.printStackTrace();
        }
        logger.info("==========购买完成==========");
        return RestDomain.success();
    }
}
